import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import '../service/ service_method.dart';
import 'dart:convert';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  int page = 1;
  List<Map> hotGoodsList = [];

  @override
  bool get wantKeepAlive => true;

  String homePageContent = '正在获取数据';

  // 获取数据类型 1:模拟数据 2:接口数据
  final int dataType = 1;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('可乐杂货铺+'),
          backgroundColor: Colors.redAccent,
        ),
        body: Container(
          child: FutureBuilder(
            future: getHomePageContext(dataType),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                var data = json.decode(snapshot.data.toString());
                // 轮播图数据
                List<Map> swiper = (data['data']['imageSource'] as List).cast();
                // 导航栏数据
                List<Map> navgatorList =
                    (data['data']['categoryList'] as List).cast();
                // 广告栏数据
                String adPicture = data['data']['adPicture']['PICTURE_ADDRESS'];
                // 拨打电话数据
                String leaderImage = data['data']['shopInfo']['leaderImage'];
                String leaderPhone = data['data']['shopInfo']['leaderPhone'];
                // 推荐商品数据
                List<Map> recommendList =
                    (data['data']['recommend'] as List).cast();
                // 楼层1数据
                String floor1Title = data['data']['floor1']['PICTURE_ADDRESS'];
                List<Map> floor1 =
                    (data['data']['floor1']['floorContent'] as List).cast();
                // 楼层2数据
                String floor2Title = data['data']['floor2']['PICTURE_ADDRESS'];
                List<Map> floor2 =
                    (data['data']['floor2']['floorContent'] as List).cast();
                // 楼层3数据
                String floor3Title = data['data']['floor3']['PICTURE_ADDRESS'];
                List<Map> floor3 =
                    (data['data']['floor3']['floorContent'] as List).cast();

                return EasyRefresh(
                    header: ClassicalHeader(
                      bgColor: Colors.lightBlueAccent,
                      textColor: Colors.pink,
                      refreshReadyText: '下拉刷新',
                      refreshingText: '刷新页面中.....',
                      refreshedText: '刷新完成啦!',
                      refreshText: '被你发现我了',
                      infoText: '@可乐杂货铺'
                    ),
                    footer: ClassicalFooter(
                      bgColor: Colors.lightBlueAccent,
                      infoText: '@可乐杂货铺',
                      loadingText: '正在加载中..',
                      loadReadyText: 'hhh',
                      noMoreText: '已经到底啦',
                      loadedText: '更多商品 敬请期待'
                    ),
                    child: ListView(
                      children: <Widget>[
                        // 轮播图
                        SwiperDiy(swiperDateList: swiper),
                        // 导航栏
                        TopNavigator(navgatorList: navgatorList),
                        // 广告
                        AdBanner(adPicture: adPicture),
                        // 店长电话
                        LeaderPhone(
                            leaderImage: leaderImage, leaderPhone: leaderPhone),
                        // 商品推荐
                        Recommend(recommendList: recommendList),
                        // 楼层一
                        FloorTitle(picture_adress: floor1Title),
                        FloorContent(floorGoodsList: floor1),
                        // 楼层二
                        FloorTitle(picture_adress: floor2Title),
                        FloorContent(floorGoodsList: floor2),
                        // 楼层三
                        FloorTitle(picture_adress: floor3Title),
                        FloorContent(floorGoodsList: floor3),
                        // 火爆专区
                        HotGoods(
                          hotGoodsList: hotGoodsList,
                        )
                      ],
                    ),
                    onRefresh: () async {
                      print("下拉");
                    },
                    onLoad: () async {
                      print('开始加载更多.....第[${page}]页');
                      await getHotGoodsContext(dataType, page).then((value) {
                        setState(() {
                          if(value != null){
                            hotGoodsList.addAll(value);
                            page++;
                          }
                        });
                      });
                    });
              } else {
                return Center(
                  child: Text('加载中......'),
                );
              }
            },
          ),
        ));
  }
}

/// 首页轮播组件
class SwiperDiy extends StatelessWidget {
  final List swiperDateList;

  SwiperDiy({Key key, this.swiperDateList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    print(
        '当前机器基础信息.....#像素:${ScreenUtil.pixelRatio} #屏幕高度:${ScreenUtil.screenHeight} #屏幕宽度:${ScreenUtil.screenWidth} ');
    return Container(
      height: ScreenUtil().setHeight(500),
      width: ScreenUtil().setWidth(720),
      child: Swiper(
        itemBuilder: (BuildContext context, int index) {
          return Image.network(
            "${swiperDateList[index]['image']}",
            fit: BoxFit.fill,
          );
          // return Image.network("http://image.zhangxinxu.com/image/study/s/s256/mm3.jpg");
        },
        itemCount: swiperDateList.length,
        pagination: new SwiperPagination(),
        autoplay: true,
      ),
    );
  }
}

/// 首页导航栏组件
class TopNavigator extends StatelessWidget {
  final List navgatorList;

  TopNavigator({Key key, this.navgatorList}) : super(key: key);

  Widget _gridViewItemUI(BuildContext context, item) {
    return InkWell(
      onTap: () {
        print('点击了${item['mallCategoryName']}');
      },
      child: Column(
        children: <Widget>[
          Image.network(item['image'], width: ScreenUtil().setWidth(95)),
          Text(item['mallCategoryName'])
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    if (this.navgatorList.length > 10) {
      this.navgatorList.removeRange(10, this.navgatorList.length);
    }
    return Container(
      height: ScreenUtil().setHeight(320),
      padding: EdgeInsets.all(3.0),
      child: GridView.count(
        physics: NeverScrollableScrollPhysics(),
        crossAxisCount: 5,
        padding: EdgeInsets.all(5.0),
        children: navgatorList.map((item) {
          return _gridViewItemUI(context, item);
        }).toList(),
      ),
    );
  }
}

/// 首页广告栏组件
class AdBanner extends StatelessWidget {
  final String adPicture;

  AdBanner({Key key, this.adPicture}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(left: 10.0, right: 10.0),
      height: ScreenUtil().setHeight(50),
      width: ScreenUtil().setWidth(720),
      child: Image.network(adPicture, fit: BoxFit.fill),
    );
  }
}

/// 店长电话模块
class LeaderPhone extends StatelessWidget {
  final String leaderImage; // 店长图片
  final String leaderPhone;

  const LeaderPhone({Key key, this.leaderImage, this.leaderPhone})
      : super(key: key); // 店长电话

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(300),
      width: ScreenUtil().setWidth(720),
      padding: EdgeInsets.all(6.0),
      child: InkWell(
        onTap: _launchURL,
        child: Image.network(leaderImage, fit: BoxFit.fill),
      ),
    );
  }

  void _launchURL() async {
    String url = 'tel:' + leaderPhone;

    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'url不能进行访问, 异常';
    }
  }
}

/// 商品推荐组件
class Recommend extends StatelessWidget {
  final List recommendList;

  const Recommend({Key key, this.recommendList}) : super(key: key);

  // 标题
  Widget _titleWidget() {
    return Container(
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.fromLTRB(10.0, 2.0, 0, 5.0),
      decoration: BoxDecoration(
          color: Colors.white,
          border:
              Border(bottom: BorderSide(width: 0.5, color: Colors.black12))),
      child: Text(
        '商品推荐',
        style: TextStyle(color: Colors.pink),
      ),
    );
  }

  // 商品单独项
  Widget _item(index) {
    return InkWell(
      onTap: () {
        print(
            '点击了推荐商品: 原价:${recommendList[index]['price']} 现价:${recommendList[index]['mallPrice']}');
      },
      child: Container(
        height: ScreenUtil().setHeight(340),
        width: ScreenUtil().setWidth(240),
        padding: EdgeInsets.all(8.0),
        decoration: BoxDecoration(
            color: Colors.white,
            border: Border(left: BorderSide(width: 1, color: Colors.black12))),
        child: Column(
          children: <Widget>[
            Image.network(recommendList[index]['image'], fit: BoxFit.fill),
            Text('￥${recommendList[index]['mallPrice']}'),
            Expanded(
              child: Text(
                '￥${recommendList[index]['price']}',
                style: TextStyle(
                    decoration: TextDecoration.lineThrough, color: Colors.grey),
              ),
            )
          ],
        ),
      ),
    );
  }

  // 横向列表方法
  Widget _recommendList() {
    return Container(
      height: ScreenUtil().setHeight(340),
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemCount: recommendList.length,
        itemBuilder: (context, index) {
          return _item(index);
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(400),
      margin: EdgeInsets.only(top: 10.0),
      child: Column(
        children: <Widget>[_titleWidget(), _recommendList()],
      ),
    );
  }
}

/// 楼层标题组件
class FloorTitle extends StatelessWidget {
  final String picture_adress;

  const FloorTitle({Key key, this.picture_adress}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.fromLTRB(50, 8, 50, 0),
      child: Image.network(picture_adress, fit: BoxFit.fill),
    );
  }
}

/// 楼层商品组件
class FloorContent extends StatelessWidget {
  final List floorGoodsList;

  const FloorContent({Key key, this.floorGoodsList}) : super(key: key);

  Widget _firstRow() {
    return Row(
      children: <Widget>[
        _goodsItem(floorGoodsList[0], 800),
        Column(
          children: <Widget>[
            _goodsItem(floorGoodsList[1], 400),
            _goodsItem(floorGoodsList[2], 400),
          ],
        )
      ],
    );
  }

  Widget _otherGoods() {
    return Row(
      children: <Widget>[
        _goodsItem(floorGoodsList[3], 400),
        _goodsItem(floorGoodsList[4], 400),
      ],
    );
  }

  Widget _goodsItem(Map goods, double height) {
    return Container(
      padding: EdgeInsets.all(10),
      width: ScreenUtil().setWidth(360),
      height: ScreenUtil().setHeight(height),
      child: InkWell(
          onTap: () {
            print('点击了楼层商品:商品名称${goods['comment']} 商品价格${goods['price']}');
          },
          child: Column(
            children: <Widget>[
              Expanded(child: Image.network(goods['image'], fit: BoxFit.fill)),
              Text(
                goods['comment'],
                style: TextStyle(color: Colors.grey),
              ),
              Text('￥${goods['price']}'),
            ],
          )),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          _firstRow(),
          _otherGoods(),
        ],
      ),
    );
  }
}

/// 火爆专区组件
class HotGoods extends StatelessWidget {
  final List hotGoodsList;

  HotGoods({Key key, this.hotGoodsList}) : super(key: key);

  Widget hotTitle = Container(
    margin: EdgeInsets.only(top: 10.0),
    alignment: Alignment.center,
    color: Colors.transparent,
    child: Text('火爆专区'),
  );

  Widget _wrapList() {
    if (hotGoodsList.length != 0) {
      List<Widget> listWidget = hotGoodsList.map((val) {
        return InkWell(
          onTap: () {},
          child: Container(
            width: ScreenUtil().setWidth(350),
            color: Colors.white,
            padding: EdgeInsets.all(5.0),
            margin: EdgeInsets.only(bottom: 3.0),
            child: Column(
              children: <Widget>[
                Image.network(val['image'], width: ScreenUtil().setWidth(340)),
                Text(
                  val['name'],
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      color: Colors.pink, fontSize: ScreenUtil().setSp(26)),
                ),
                Row(
                  children: <Widget>[
                    Text('￥${val['malPrice']}'),
                    Text(
                      '￥${val['price']}',
                      style: TextStyle(
                        color: Colors.black12,
                        decoration: TextDecoration.lineThrough,
                      ),
                    )
                  ],
                )
              ],
            ),
          ),
        );
      }).toList();
      return Wrap(
        spacing: 2,
        children: listWidget,
      );
    } else {
      return Text('下拉刷新 ');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          hotTitle,
          _wrapList(),
        ],
      ),
    );
  }
}
